<?php

// +----------------------------------------------------------------------
// | 第三方支付
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2022 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\pay;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\app\ThirdRechargeOrder as ThirdRechargeOrderModel;
use app\model\index\Order as OrderModel;
use app\model\ucenter\UserCash as UserCashModel;
use app\model\ucenter\UserTask as UserTaskModel;
use app\ucenter\event\UserAuth as UserAuthEvent;
use think\facade\Db;
use app\model\ucenter\User as UserModel;
use app\pay\model\Pay as PayModel;
use think\Exception;
use think\facade\Lang;
use app\model\pay\PointOrder as PointOrderModel;
use app\model\pay\PointProduct as PointProductModel;

class PointOrder extends Base
{


    public function fail()
    {
        $orders = PointOrderModel::where('status', 1)->where('step', 0)->whereTime('create_time', '<', '-3 day')->select();
        foreach ($orders as $order) {
            $order['step'] = 3;
            $order->save();
            $task = UserTaskModel::where('task_type', 25)->where('relation_id', $order['id'])->find();
            if ($task) {
                $task['reason'] = '超时未支付';
                $task['status'] = 3;
                $task->save();
            }
        }
    }

    /**
     * 通用更新方法
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function update($param, $admin = null)
    {
        try {
            if (empty($param)) {
                throw new Exception(Lang::get('__data_format_error_'));
            }
            if (!empty($param['id'])) {
                // 更新操作
                $order = PointOrderModel::where('id', $param['id'])->where('status', 1)->find();
                if ($order) {
                    $order['step'] = $param['step'];
                    $order['price'] = $param['price'];
                    $order['point'] = $param['point'];
                    $order['free_balance'] = $param['free_balance'];
                    if ($order['step'] == 2 || $order['step'] == 3) {
                        $order['status'] = 2;
                    }
                    $order->save($param);
                    if ($order['step'] == 2 || $order['status'] == 3 || $order['status'] == 1) {
                        $task = UserTaskModel::where('relation_id', $order['id'])->where('task_type', 25)->find();
                        if ($task) {
                            $task['step'] = $order['step'];
                            $task['money'] = $order['price'];
                            $task['commission'] = $order['price'];
                            if ($order['step'] == 2) {
                                $task['status'] = 2;
                                $user = UserModel::where('id', $order['user_id'])->find();
                                if ($user) {
                                    UserEvent::exhibitionIncome($user, $task['commission'], $task['title'], 50, $user['id'], $order['id'], 0, $order['product_id'], 2);
                                    if ($order['free_balance'] > 0) {
                                        UserEvent::freeIncome($user, $order['free_balance'], '积分兑换本金退回（该金额不参与云副业收益规则，提现无需扣税）', 88, $user['id'], $order['id'], 0, $order['product_id'], 2);
                                    }
                                }
                            } elseif ($order['step'] == 3) {
                                $task['status'] = 3;
                            } else {
                                $task['status'] = 1;
                            }
                            $task->save();
                        }
                    }
                }
                $data['message'] = '操作成功';
            } else { // 新增
                $result = $this->model::create($param);
            }
            $data['code'] = 0;
            $data['message'] = '操作成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    public function add($param, $user)
    {
        try {

            if (!$user) {
                throw new Exception('请先登录');
            }

            //根据id获取产品详情
            $productInfo = PointProductModel::where('id', $param['product_id'])->find();
            if (!$productInfo) {
                throw new Exception('此产品暂时无法申请');
            }


            $productInfo['apply_num'] = $productInfo['apply_num'] + 1;
            $productInfo['virtual_num'] = $productInfo['virtual_num'] + rand(5, 20);
            $productInfo->save();
            Db::startTrans();
            // 查询当天是否申请
            $order = PointOrderModel::where('product_id', $productInfo['id'])->where('user_id', $user['id'])->whereTime('update_time', 'today')
                ->where('status', 1)->find();
            if (!$order) {
                $insert = [
                    'user_id' => $user['id'],
                    'name' => $productInfo['name'],
                    'chaxun' => $productInfo['chaxun'],
                    'flag' => $productInfo['flag'],
                    'product_id' => $productInfo['id'],
                    'step' => 0,
                    'price' => 0,
                    'point' => 0,
                ];
                $order = PointOrderModel::create($insert);
                if (!$order) {
                    throw new Exception('系统故障');
                }
                $task_insert = [
                    'user_id' => $user['id'],
                    'agent_id' => $user['agent_id'],
                    'step' => 0,
                    'status' => 0,
                    'title' => $productInfo['name'],
                    'task_id' => $productInfo['id'],//改换mobile_task_id
                    'submit_info' => $param,
                    'task_type' => 25,
                    'createtime' => time(),
                    'updatetime' => time(),
//                    'end_time' => time() + 30 * 86400,
                    'money' => $productInfo['commission'],
                    'commission' => $productInfo['commission'],
                    'relation_id' => $order['id']
                ];
                $task = UserTaskModel::create($task_insert);
                if (!$task) {
                    throw new Exception('系统故障');
                }
            } else {
                $order['update_time'] = time_format();
                $order->save();
            }


            Db::commit();
            $data['code'] = 0;
            $data['data']['url'] = 'https://work.weixin.qq.com/kfid/kfcc0399e043016da49';
            $data['message'] = 'ok';
            $data['code'] = 0;
        } catch (Exception $exception) {
            Db::rollback();
            $data['message'] = $exception->getMessage();
            $data['code'] = 1;
        }
        return $data;
    }


}
